// dashboard.js
// 仪表盘页面专用脚本

// 等待认证管理器初始化
document.addEventListener('DOMContentLoaded', function() {
    const checkAuth = () => {
        if (window.AuthManager) {
            initDashboard();
        } else {
            setTimeout(checkAuth, 100);
        }
    };
    checkAuth();
});

function initDashboard() {
    console.log('初始化仪表盘...');
    console.log('AuthManager:', window.AuthManager);
    
    // 检查认证状态
    if (!window.AuthManager.isAuthenticated()) {
        console.log('用户未认证，重定向到登录页面');
        window.location.href = '/ercms/login';
        return;
    }
    
    const userInfo = window.AuthManager.getUserInfo();
    console.log('用户信息:', userInfo);
    
    if (!userInfo) {
        console.log('未找到用户信息，尝试重新验证token');
        // 尝试重新验证token而不是直接重定向
        window.AuthManager.verifyToken()
            .then(() => {
                console.log('Token验证成功，重新初始化仪表盘');
                initDashboard();
            })
            .catch(() => {
                console.log('Token验证失败，重定向到登录页面');
                window.location.href = '/ercms/login';
            });
        return;
    }

    // 更新用户信息显示
    updateUserInfo(userInfo);
    
    // 根据用户角色显示调度卡片
    if (window.AuthManager.hasAnyRole(['DISPATCHER', 'ADMIN'])) {
        document.getElementById('dispatch-card').style.display = 'block';
    }

    // 加载仪表盘数据
    console.log('开始加载仪表盘数据...');
    loadDashboardStats();
    loadRecentEvents();
}

function updateUserInfo(userInfo) {
    const userWelcome = document.getElementById('user-welcome');
    const userRole = document.getElementById('user-role');
    
    if (userWelcome) {
        userWelcome.textContent = `👋 欢迎回来，${userInfo.realName || userInfo.username}`;
    }
    
    if (userRole) {
        let badgeHtml = '';
        let roleIcon = '';
        switch (userInfo.role) {
            case 'ADMIN':
                roleIcon = '<i class="bi bi-shield-check"></i>';
                badgeHtml = '<span class="badge bg-primary">系统管理员</span>';
                break;
            case 'DEPT_MANAGER':
                roleIcon = '<i class="bi bi-building"></i>';
                badgeHtml = '<span class="badge bg-success">部门管理员</span>';
                break;
            case 'DISPATCHER':
                roleIcon = '<i class="bi bi-headset"></i>';
                badgeHtml = '<span class="badge bg-warning text-dark">调度员</span>';
                break;
            case 'END_USER':
                roleIcon = '<i class="bi bi-person"></i>';
                badgeHtml = '<span class="badge bg-secondary">终端用户</span>';
                break;
            default:
                roleIcon = '<i class="bi bi-person"></i>';
                badgeHtml = `<span class="badge bg-secondary">${userInfo.role}</span>`;
        }
        userRole.innerHTML = `${roleIcon} ${badgeHtml}`;
    }
}

// 仪表盘统计数据加载
function loadDashboardStats() {
    const headers = window.AuthManager.getAuthHeaders();
    fetch('/ercms/api/dashboard/stats', {
        headers: headers
    })
        .then(resp => resp.json())
        .then(res => {
            if(res.success) {
                const d = res.data;
                document.getElementById('pending-events-count').textContent = d.pendingEvents ?? '-';
                document.getElementById('inprogress-events-count').textContent = d.inProgressEvents ?? '-';
                document.getElementById('available-resources-count').textContent = d.availableResources ?? '-';
                document.getElementById('active-users-count').textContent = d.activeUsers ?? '-';
            }
        })
        .catch(error => {
            console.error('加载统计数据失败:', error);
        });
}

// 坐标反解缓存
const geocodeCache = new Map();

// 坐标反解为地址
async function reverseGeocode(lng, lat) {
    if (!lng || !lat) return '';
    
    // 检查缓存
    const cacheKey = `${lng},${lat}`;
    if (geocodeCache.has(cacheKey)) {
        return geocodeCache.get(cacheKey);
    }
    
    try {
        return new Promise((resolve, reject) => {
            AMap.plugin('AMap.Geocoder', function() {
                const geocoder = new AMap.Geocoder();
                geocoder.getAddress([lng, lat], (status, result) => {
                    if (status === 'complete' && result.info === 'OK') {
                        const address = result.regeocode.formattedAddress;
                        // 缓存结果
                        geocodeCache.set(cacheKey, address);
                        resolve(address);
                    } else {
                        const errorMsg = '坐标解析失败';
                        geocodeCache.set(cacheKey, errorMsg);
                        resolve(errorMsg);
                    }
                });
            });
        });
    } catch (error) {
        console.error('地址解析失败:', error);
        const errorMsg = '坐标解析失败';
        geocodeCache.set(cacheKey, errorMsg);
        return errorMsg;
    }
}

// 批量坐标反解为地址
async function batchReverseGeocode(events) {
    const geocodePromises = events.map(async (event) => {
        // 检查location字段是否为坐标格式
        const locationStr = event.location || '';
        const isCoordinate = /^-?\d+\.?\d*,\s*-?\d+\.?\d*$/.test(locationStr);
        
        if (locationStr && !isCoordinate) {
            // 如果location存在且不是坐标格式，直接使用
            return { ...event, displayLocation: locationStr };
        } else if (isCoordinate) {
            // 如果是坐标格式，进行反解
            const [lng, lat] = locationStr.split(',').map(coord => parseFloat(coord.trim()));
            try {
                console.log(`反解坐标字符串: ${locationStr} -> lng: ${lng}, lat: ${lat}`);
                const address = await reverseGeocode(lng, lat);
                return { ...event, displayLocation: address || '坐标解析中...' };
            } catch (error) {
                console.error('坐标反解失败:', error);
                return { ...event, displayLocation: '坐标解析失败' };
            }
        } else if (event.currentLongitude && event.currentLatitude) {
            // 使用单独的经纬度字段
            try {
                console.log(`反解经纬度字段: lng: ${event.currentLongitude}, lat: ${event.currentLatitude}`);
                const address = await reverseGeocode(event.currentLongitude, event.currentLatitude);
                return { ...event, displayLocation: address || '坐标解析中...' };
            } catch (error) {
                console.error('坐标反解失败:', error);
                return { ...event, displayLocation: '坐标解析失败' };
            }
        } else {
            return { ...event, displayLocation: '未知地点' };
        }
    });
    
    return Promise.all(geocodePromises);
}

// 清除坐标反解缓存
function clearGeocodeCache() {
    geocodeCache.clear();
    console.log('坐标反解缓存已清除');
}

// 获取缓存统计信息
function getGeocodeCacheStats() {
    return {
        size: geocodeCache.size,
        keys: Array.from(geocodeCache.keys())
    };
}

// 加载最近事件
async function loadRecentEvents() {
    try {
        const headers = window.AuthManager.getAuthHeaders();
        const response = await fetch('/ercms/api/events/recent', {
            headers: headers
        });
        const result = await response.json();
        
        const tbody = document.getElementById('recent-events-tbody');
        
        if (result.success && result.data && result.data.length > 0) {
            // 先显示加载状态
            let html = '';
            const eventsToShow = result.data.slice(0, 5); // 只显示最近5个事件
            
            for (const event of eventsToShow) {
                const statusText = getStatusText(event.status);
                const statusClass = getStatusClass(event.status);
                
                // 检查location是否为坐标格式
                const locationStr = event.location || '';
                const isCoordinate = /^-?\d+\.?\d*,\s*-?\d+\.?\d*$/.test(locationStr);
                const displayLocation = isCoordinate ? '坐标解析中...' : (locationStr || '未知地点');
                
                html += `
                    <tr>
                        <td>${event.title || '未命名事件'}</td>
                        <td>${event.eventType ? event.eventType.name : '未知类型'}</td>
                        <td class="location-cell" data-lng="${event.currentLongitude || ''}" data-lat="${event.currentLatitude || ''}" data-location="${event.location || ''}">
                            ${displayLocation}
                        </td>
                        <td><span class="badge ${statusClass}">${statusText}</span></td>
                        <td>${formatDateTime(event.startTime)}</td>
                        <td>
                            <a href="/ercms/dispatch/event/${event.id}" class="btn btn-sm btn-primary">查看详情</a>
                        </td>
                    </tr>
                `;
            }
            
            tbody.innerHTML = html;
            
            // 异步处理坐标反解
            setTimeout(async () => {
                try {
                    console.log('开始批量坐标反解...');
                    const eventsWithLocation = await batchReverseGeocode(eventsToShow);
                    console.log('批量坐标反解完成:', eventsWithLocation);
                    
                    // 更新表格中的地点信息
                    const locationCells = tbody.querySelectorAll('.location-cell');
                    eventsWithLocation.forEach((event, index) => {
                        if (locationCells[index]) {
                            locationCells[index].textContent = event.displayLocation;
                        }
                    });
                    
                    // 显示缓存统计信息
                    const cacheStats = getGeocodeCacheStats();
                    console.log('坐标反解缓存统计:', cacheStats);
                    
                } catch (error) {
                    console.error('批量坐标反解失败:', error);
                    // 如果批量反解失败，尝试逐个反解
                    const locationCells = tbody.querySelectorAll('.location-cell');
                    locationCells.forEach(async (cell, index) => {
                        const lng = cell.dataset.lng;
                        const lat = cell.dataset.lat;
                        const location = cell.dataset.location;
                        
                        // 检查location是否为坐标格式
                        const isCoordinate = /^-?\d+\.?\d*,\s*-?\d+\.?\d*$/.test(location);
                        
                        if (isCoordinate) {
                            // 如果是坐标格式，进行反解
                            const [coordLng, coordLat] = location.split(',').map(coord => parseFloat(coord.trim()));
                            try {
                                console.log(`单个反解坐标字符串: ${location} -> lng: ${coordLng}, lat: ${coordLat}`);
                                const address = await reverseGeocode(coordLng, coordLat);
                                if (address) {
                                    cell.textContent = address;
                                    console.log(`坐标反解成功: ${location} -> ${address}`);
                                }
                            } catch (error) {
                                console.error('单个坐标反解失败:', error);
                            }
                        } else if (!location && lng && lat) {
                            // 使用单独的经纬度字段
                            try {
                                console.log(`尝试反解坐标: ${lng}, ${lat}`);
                                const address = await reverseGeocode(lng, lat);
                                if (address) {
                                    cell.textContent = address;
                                    console.log(`坐标反解成功: ${lng}, ${lat} -> ${address}`);
                                }
                            } catch (error) {
                                console.error('单个坐标反解失败:', error);
                            }
                        }
                    });
                }
            }, 100);
            
        } else {
            tbody.innerHTML = '<tr><td colspan="6" style="text-align:center;">暂无最近事件</td></tr>';
        }
    } catch (error) {
        console.error('加载最近事件失败:', error);
        document.getElementById('recent-events-tbody').innerHTML = 
            '<tr><td colspan="6" style="text-align:center;color:red;">加载失败</td></tr>';
    }
}

// 获取状态文本
function getStatusText(status) {
    const statusMap = {
        'PENDING': '待处理',
        'IN_PROGRESS': '进行中',
        'COMPLETED': '已完成',
        'CANCELLED': '已取消'
    };
    return statusMap[status] || status;
}

// 获取状态样式类
function getStatusClass(status) {
    const classMap = {
        'PENDING': 'bg-warning',
        'IN_PROGRESS': 'bg-primary',
        'COMPLETED': 'bg-success',
        'CANCELLED': 'bg-secondary'
    };
    return classMap[status] || 'bg-secondary';
}

// 格式化日期时间
function formatDateTime(dateTimeStr) {
    if (!dateTimeStr) return '-';
    
    try {
        const date = new Date(dateTimeStr);
        return date.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit'
        });
    } catch (error) {
        return dateTimeStr;
    }
}

// 退出登录
function logout() {
    if (confirm('确定要退出登录吗？')) {
        window.AuthManager.logout();
    }
}

// 测试坐标反解功能
async function testReverseGeocode() {
    console.log('开始测试坐标反解功能...');
    
    // 测试坐标字符串格式
    const testCoordinate = '127.159296,45.754132';
    console.log(`测试坐标: ${testCoordinate}`);
    
    try {
        const [lng, lat] = testCoordinate.split(',').map(coord => parseFloat(coord.trim()));
        console.log(`解析后的坐标: lng=${lng}, lat=${lat}`);
        
        const address = await reverseGeocode(lng, lat);
        console.log(`反解结果: ${address}`);
        
        // 显示缓存统计
        const cacheStats = getGeocodeCacheStats();
        console.log('缓存统计:', cacheStats);
        
    } catch (error) {
        console.error('测试坐标反解失败:', error);
    }
}

// 在页面加载完成后测试坐标反解
// 延迟5秒后测试坐标反解功能
document.addEventListener('DOMContentLoaded', function() {
    setTimeout(() => {
        if (window.AuthManager && window.AuthManager.isAuthenticated()) {
            testReverseGeocode();
        }
    }, 5000);
}); 